import React from 'react';
import {Spin, Card, Button, Row, Col, Form, Input} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {injectIntl} from './intl';
import styles from './style.css';
import TextInput from 'Shared/components/TextInput';
import Return from '../common/Return';
import {newOrUpdateValidator} from './validator';
import {getDetail, getVehicleSoldsQuickly} from './api';
import {dealerType, vehicleStatus} from '../Enum';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import VehicleSoldSelectPanel from './VehicleSoldSelectPanel';
import SearchSelect from 'Shared/components/SearchSelect';
import WrappedDatePicker from '../common/WrappedDatePicker';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
const FormItem = Form.Item;
const dealerConditions = {
    type: dealerType.经销商
};
class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        showVehicle: false
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }
    vehicleLabelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `${d.vin}`;
        return '';
    }
    getDetailInfo = () => {
        if(this.props.id)
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            isFetching: false,
                            data: res.data,
                        });
                    else
                        this.setState(({
                            isFetching: false
                        }));
                });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSelectDealer = data => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                subDealerId: data.id,
                subDealerCode: data.code,
                subDealerName: data.name,
            }),
            hasOperat: true
        });
    }
    onSearchVehicle = value => getVehicleSoldsQuickly({
        filter: value,
        status: vehicleStatus.实销完成
    })
        .then(res => {
            const data = res.data;
            if(data)
                return data.content;
        });
    onSelectVehicle = data => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                vehicleId: data.id,
                vin: data.vin,
                mileage: data.mileage,
            }),
            showVehicle: false,
            hasOperat: true
        });
    }
    onClickVehicle = e => {
        e.stopPropagation();
        this.setState({showVehicle: true});
    }
    onCloseVehicle = () => {
        this.setState({showVehicle: false});
    }
    onSubmit = () => {
        const {data} = this.state;
        const isValid = newOrUpdateValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, loading} = this.state;
        const validateRemark = data.remark && data.remark.length > 250 && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.add, this.props.permissions) || !hasPermissions(PERMISSION.update, this.props.permissions);
        const dealerInfo = data.subDealerId ? {
            id: data.subDealerId,
            code: data.subDealerCode,
            name: data.subDealerName
        } : null;
        const vehicleInfo = data.vehicleId ? {
            id: data.vehicleId,
            vin: data.vin
        } : null;
        if(this.props.enterprise)
            data.subDealerId = this.props.enterprise.id;
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'newPanel.column.common',
                        defaultMessage: '基本信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem class={styles.multiLabel} label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '编号'
                                    })}
                                    {...FORM_OPTIONS.item} >
                                        <Input placeholder={formatMessage({
                                            id: 'newPanel.operation.notGenerate',
                                            defaultMessage: '尚未生成'
                                        })} value={data.code} disabled />
                                    </FormItem>
                                </Col>
                                {!this.props.enterprise && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.subDealer',
                                        defaultMessage: '经销商'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.subDealerId && this.state.validate ? 'error' : null}
                                    required>
                                        <DealerSelectPanel
                                            conditions={dealerConditions}
                                            value={dealerInfo}
                                            onSelect={this.onSelectDealer} />
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.repairOrder',
                                        defaultMessage: '派工单号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.repairOrder && this.state.validate ? 'error' : null}
                                    required>
                                        <TextInput
                                            name="repairOrder"
                                            value={data.repairOrder}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.vin',
                                        defaultMessage: 'VIN'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.vin && this.state.validate ? 'error' : null}
                                    required>
                                        {!this.props.id && <SearchSelect
                                            value={vehicleInfo}
                                            placeholder={this.props.intl.formatMessage({
                                                id: 'newPanel.form.vin.placeholder',
                                                defaultMessage: '请输入VIN进行查询'
                                            })}
                                            onSelect={this.onSelectVehicle}
                                            onSearch={this.onSearchVehicle}
                                            keyIndex="id"
                                            labelMap={this.vehicleLabelMap}
                                            onClickSearchBtn={this.onClickVehicle} />
                                        }
                                        {this.props.id && data.vin}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.maintainDate',
                                            defaultMessage: '保养日期'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={!data.maintainDate && this.state.validate ? 'error' : null}
                                        required>
                                        <WrappedDatePicker
                                            name="maintainDate"
                                            value={data.maintainDate}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.mileage',
                                            defaultMessage: '行驶里程'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={!data.mileage && this.state.validate ? 'error' : null}
                                        required>
                                        <LocalizeInputNumber
                                            name="mileage"
                                            value={data.mileage}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem {...FORM_ROW_OPTIONS.item} label={formatMessage({
                                    id: 'newPanel.operation.remark',
                                    defaultMessage: '备注'
                                })} validateStatus={validateRemark}>
                                    <TextInput
                                        type="textarea"
                                        name="remark"
                                        value={data.remark}
                                        onBlur={this.onChange} />
                                </FormItem>
                            </Row>
                        </Form>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showVehicle &&
                        <VehicleSoldSelectPanel
                            isOtherArea={data.isOtherArea}
                            selectKey={data.vehicleSoldId}
                            onCancel={this.onCloseVehicle}
                            onSelect={this.onSelectVehicle} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    enterprise: PropTypes.object,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onNewOrUpdate
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getEnterprise = selectorFactory(['page', 'domainData', 'initData', 'enterprise']);
const mapStateToProps = (state, props) => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isCompanyUser'])),
    permissions: getPermissions(state),
    enterprise: getEnterprise(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: data => dispatch(onNewOrUpdate(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
